<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'add' ? '新增' : pageType === 'edit' ? '编辑' : '详情'}-销售订单`"
		width="1100px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:append-to-body="false"
		:show-close-btn="pageType === 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-confirm-btn="pageType !== 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="margin-bottom-4 flex-between-center" style="align-items: flex-end;">
					<div class="flex-start-center" style="font-size: 13px;">
						<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
							<span class="el-icon-tickets item-gap"></span>
							<span>基本信息</span>
						</el-tag>
						<div v-else style="font-size: 16px;">
							<span class="el-icon-star-off item-gap"></span>
							<span>{{ ruleForm.code }}</span>
						</div>
					<!--<el-tag v-if="ruleForm.id" size="mini" type="info"><jk-state-bar :state="ruleForm.serviceState" :state-list="saleOrderStateList"></jk-state-bar></el-tag>-->
					</div>
					<div v-if="ruleForm.id && showDialog">
						<order-list-popover-bar :rule-form="ruleForm" @on-leave="onVisibleChange(false)"></order-list-popover-bar>
					</div>
				</div>
				<jk-card class="">
					<el-row ref="box2">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="客户" prop="customerId">
								<span v-if="pageType === 'detail' || (ruleForm.serviceState && ruleForm.serviceState !== 1)" class="read-only-2">{{ ruleForm.customerName }}</span>
								<remote-search-customer-input
									v-else
									placeholder="客户"
									only-key="customerId"
									query-name="customerName"
									:form-data="ruleForm"
									@on-select="onSelectCustomerChange"
								></remote-search-customer-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="业务员">
								<span class="read-only-2">{{ ruleForm.salesmanName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="销售部门">
								<span class="read-only-2">{{ ruleForm.deptName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="交货截止日">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.deliveryDateTo }}</span>
								<jk-date-picker v-else v-model="ruleForm.deliveryDateTo" size="medium" placeholder="交货截止日"></jk-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="单据日期" prop="saleOrderDate">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.saleOrderDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.saleOrderDate" size="medium" placeholder="单据日期"></jk-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.remark }}</span>
								<jk-input v-else v-model="ruleForm.remark" type="textarea" :rows="2" size="medium" placeholder="请输入"></jk-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<el-tag class="margin-top-10 margin-bottom-4" effect="plain"><i class="el-icon-postcard"></i> 品种信息</el-tag>
			<jk-table :data="ruleForm.productList || []" :height="dialogTableHeight + 40">
				<vxe-column type="expand" title="展开" align="center" :width="60">
					<template #content="{ row, rowIndex }">
						<el-row class="flex-start-center-wrap margin-top-10" style="padding-right: 10px;">
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="销售工艺">
									<jk-input v-model="row.batchOne" placeholder="" disabled size="mini"></jk-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="特殊要求">
									<jk-input v-model="row.specialRequirement" placeholder="" disabled size="mini"></jk-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="用棉要求">
									<jk-input v-model="row.cottonRequirement" placeholder="" disabled size="mini"></jk-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="纺纱要求">
									<jk-input v-model="row.spinRequirement" placeholder="" disabled size="mini"></jk-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="产品用途">
									<jk-input v-model="row.productUse" placeholder="" disabled size="mini"></jk-input>
								</el-form-item>
							</el-col>
						</el-row>
					</template>
				</vxe-column>
				<vxe-column :visible="pageType !== 'detail'" title="操作" align="center" field="saleOrderQty" :width="70">
					<template slot="header">
						<div class="flex-center">
							<jk-button type="text" class="item-gap" size="mini" @click="onAddBtn"><span class="el-icon-plus"></span>添加</jk-button>
						</div>
					</template>
					<template slot-scope="scope">
						<div class="flex-center">
							<!--<jk-button icon="el-icon-plus" class="item-gap" size="mini" @click="onAddBtn(scope.rowIndex)"></jk-button>-->
							<jk-button icon="el-icon-minus" size="mini" @click="ruleForm.productList.splice(scope.rowIndex, 1)"></jk-button>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="品种" align="left" field="productName" :min-width="200">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)">{{ scope.row.productName }}</span>
						<remote-search-product-input
							v-else
							:is-valid-date="true"
							placeholder="品种"
							default-stock-type="FINISHED_PRODUCT"
							only-key="productId"
							query-name="productName"
							size="mini"
							:form-data="scope.row"
							@on-select="onSelectProductChange($event, scope.rowIndex)"
						></remote-search-product-input>
					</template>
				</vxe-column>
				<vxe-column title="规格" align="left" field="productModels" :width="120"></vxe-column>
				<vxe-column title="单位" align="left" field="unitName" :width="60"></vxe-column>
				<vxe-column title="数量" align="right" field="saleOrderQty" :width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)">{{ scope.row.saleOrderQty }}</span>
						<jk-number-input v-else v-model="scope.row.saleOrderQty" :disabled="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)" placeholder="数量" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<vxe-column title="交货截止日" align="left" field="deliveryDateTo" :width="152">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)">{{ scope.row.deliveryDateTo }}</span>
						<jk-date-picker v-else v-model="scope.row.deliveryDateTo" :disabled="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)" size="mini"></jk-date-picker>
					</template>
				</vxe-column>
				<vxe-column title="说明" align="left" field="remark" :width="140">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)">{{ scope.row.remark }}</span>
						<jk-input v-else v-model="scope.row.remark" :disabled="pageType === 'detail' || (scope.row.serviceState && scope.row.serviceState !== 1)" type="textarea" :rows="1" size="mini"></jk-input>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import {
        productionSaleOrderCreate,
        productionSaleOrderGet, productionSaleOrderUpdate
    } from '../../../api/production/order';
    import remoteSearchCustomerInput from '../order/components/remote-search-customer-input';
    import remoteSearchProductInput from '../order/components/remote-search-product-input';
    import { formatDate } from '../../../utils/jk/jk-tool';
    import orderListPopoverBar from './components/order-list-popover-bar';
    import { saleOrderStateList } from '../../../utils/jk/status-option-list';
    import calTableHeight from '../../../mixins/cal-dialog-height';
    export default {
        mixins: [calTableHeight],
        components: {
            orderListPopoverBar,
            remoteSearchProductInput,
            remoteSearchCustomerInput
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            pageType: {
                type: String,
                default: 'add'
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                saleOrderStateList: saleOrderStateList,
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    saleOrderSalesmanName: '',
                    saleOrderQty: null,
                    saleOrderDate: '',
                    customerId: null,
                    customerCode: '',
                    customerName: '',
                    settleCustomerId: null,
                    settleCustomerCode: '',
                    settleCustomerName: '',
                    productId: null,
                    productCode: '',
                    productName: '',
                    productModels: '',
                    deliveryDateTo: '',
                    unitId: null,
                    unitCode: '',
                    unitName: '',
                    remark: '',
                    saleOrderDeptName: '',
                    productList: []
                },
                rules: {
                    customerId: [{ required: true, trigger: 'change' }],
                    productId: [{ required: true, trigger: 'change' }],
                    saleOrderQty: [{ required: true, trigger: 'change' }],
                    saleOrderDate: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onAddBtn(rowIndex) {
                const item = {
                    productId: null,
                    productCode: '',
                    productName: '',
                    productModels: '',
                    unitId: null,
                    unitCode: '',
                    unitName: '',
                    saleOrderQty: 0,
                    deliveryDateTo: ''
                };
                if (rowIndex || rowIndex === 0) {
                    this.ruleForm.productList.splice(rowIndex + 1, 0, item);
                } else {
                    this.ruleForm.productList.push(item);
                }
            },
            onSelectProductChange(e, rowIndex) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm.productList[rowIndex], 'productId', e.id);
                    this.$set(this.ruleForm.productList[rowIndex], 'productCode', e.code);
                    this.$set(this.ruleForm.productList[rowIndex], 'productName', e.name);
                    this.$set(this.ruleForm.productList[rowIndex], 'productModels', e.models);
                    this.$set(this.ruleForm.productList[rowIndex], 'unitId', e.unitId);
                    this.$set(this.ruleForm.productList[rowIndex], 'unitCode', e.unitCode);
                    this.$set(this.ruleForm.productList[rowIndex], 'unitName', e.unitName);
                    this.$set(this.ruleForm.productList[rowIndex], 'tenPrice', e.tenPrice);
                    this.$set(this.ruleForm.productList[rowIndex], 'yarnCount', e.yarnCount);
                    this.$set(this.ruleForm.productList[rowIndex], 'yarnColorName', e.yarnColorName);
                    this.$set(this.ruleForm.productList[rowIndex], 'criterion', e.criterion);
                }
            },
            onSelectCustomerChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'customerId', e.id);
                    this.$set(this.ruleForm, 'customerCode', e.code);
                    this.$set(this.ruleForm, 'customerName', e.name);
                    this.$set(this.ruleForm, 'settleCustomerId', e.settleCustomerId);
                    this.$set(this.ruleForm, 'settleCustomerCode', e.settleCustomerCode);
                    this.$set(this.ruleForm, 'settleCustomerName', e.settleCustomerName);
                }
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? productionSaleOrderCreate : productionSaleOrderUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionSaleOrderGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'saleOrderDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'deliveryDateTo', formatDate(Date.now() + 7 * 24 * 60 * 60 * 1000));
                }
                if (this.dataId) await this.getDetailRequest();
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
// 解决在生产订单编辑页打开时全局的margin-bottom-10被覆盖的问题
.margin-bottom-10 {
    margin-bottom: 10px;
}
</style>
